<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-left">
        <div class="brand-logo">
          <img src="../assets/icons/logo.png" alt="轻聊Logo">
        </div>
        <div class="brand-features">
          <div class="feature-item">
            <span class="feature-icon">💬</span>
            <p>随时随地，轻松聊天</p>
          </div>
          <div class="feature-item">
            <span class="feature-icon">🔒</span>
            <p>安全可靠的通信保障</p>
          </div>
          <div class="feature-item">
            <span class="feature-icon">🚀</span>
            <p>快速流畅的即时响应</p>
          </div>
        </div>
      </div>
      <div class="login-right">
        <div class="welcome-image">
          <img src="../assets/icons/welcome.png" alt="欢迎回来">
        </div>
        <p class="subtitle">{{ isRegistering ? '创建新账号' : '登录您的账号' }}</p>

        <!-- 使用 v-show 切换显示不同的表单 -->
        <form @submit.prevent="chooseForm" class="login-form">
          <div class="input-group">
            <input
              type="text"
              v-model="form.username"
              placeholder="用户名"
              required
              name="username"
            >
          </div>
          <div class="input-group">
            <input
              type="password"
              v-model="form.password"
              placeholder="密码"
              required
              name="password"
            >
          </div>
          <div v-if="isRegistering" class="input-group">
            <input
              type="password"
              v-model="form.confirmPassword"
              placeholder="确认密码"
              required
              name="confirmPassword"
            >
          </div>
          <div class="error-msg" id="errorMsg">{{ errorMessage }}</div>
          <button type="button" @click="chooseForm" class="login-btn">{{ isRegistering ? '注册' : '登录' }}</button>
        </form>

        <!-- 切换到注册/登录 -->
        <div class="register-link">
          <span v-if="!isRegistering">还没有账号？<a href="#" @click.prevent="toggleForm">立即注册</a></span>
          <span v-if="isRegistering">已有账号？<a href="#" @click.prevent="toggleForm">返回登录</a></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import socket from '../utils/socket'
import { useUserStore } from '../stores/user'
import { userIdStore } from '../utils/id';
import { onMounted, onUnmounted } from 'vue'

const router = useRouter()
const userStore = useUserStore()
const idStore = userIdStore()

const isRegistering = ref(false)
const form = ref({
  username: '',
  password: '',
  confirmPassword: ''
})
const errorMessage = ref('')

const toggleForm = () => {
  isRegistering.value = !isRegistering.value;
  errorMessage.value = '';  // 清除错误信息
}


const chooseForm = () => {
    console.log("click");
    if(isRegistering.value){
      handleRegister();
    }else{
      handleLogin();
    }
}
const handleLogin = () => {
  // 登录逻辑
  const data = {
    type: "LOGIN",
    payload: {
      username: form.value.username,
      password: form.value.password
    },
    timestamp: new Date().toISOString()
  };
  console.log("发送内容字符串:", JSON.stringify(data));
  socket.send(JSON.stringify(data));
  socket.addEventListener('message', (event) => {
    const response = JSON.parse(event.data);
    if (response.responseMsg === "登录成功") {
      userStore.login(form.value.username, form.value.password);
      idStore.setId(response.data);
      router.push('/chat');
    } else if (response.responseMsg === "用户名或密码错误") {
      errorMessage.value = '用户名或密码错误！';
    }
  });
}

// socket.onmessage = (event) => {
//   const response = JSON.parse(event.data);
//   console.log("收到服务端消息：", response);

//   if (response.type === "LOGIN") {
//     if (response.responseMsg === "登录成功") {
//       userStore.login(form.value.username, form.value.password);
//       idStore.setId(response.data);
//       router.push('/chat');
//     } else {
//       errorMessage.value = '用户名或密码错误！';
//     }
//   } else if (response.type === "REGISTER") {
//     if (response.responseMsg === "注册成功") {
//       errorMessage.value = '注册成功！';
//       isRegistering.value = false;
//     } else if (response.responseMsg === "用户名已存在") {
//       errorMessage.value = '该用户名已被注册！';
//     }
//   }
// };
// socket.onopen = () => {
//   console.log("WebSocket连接成功，准备发送登录信息");
// };
// 移除之前的 socket.onmessage，统一使用 addEventListener
const messageHandler = (event) => {
  const response = JSON.parse(event.data);
  console.log("收到服务端消息：", response);

  if (response.responseMsg === "登录成功") {
    console.log("登录成功，准备跳转");
    userStore.login(form.value.username, form.value.password);
    idStore.setId(response.data);
    // 确保在成功登录后立即跳转
    router.push('/chat');
  } else if (response.responseMsg === "用户名或密码错误") {
    errorMessage.value = '用户名或密码错误！';
  } else if (response.responseMsg === "注册成功") {
    errorMessage.value = '注册成功！';
    isRegistering.value = false;
  } else if (response.responseMsg === "用户名已存在") {
    errorMessage.value = '该用户名已被注册！';
  }
};

socket.onopen = () => {
  console.log("WebSocket连接成功，准备发送登录信息");
};

const handleRegister = () => {
  console.log("handleRegister 被触发"); // 调试日志
  errorMessage.value = "注册按钮已点击（测试）"; 
  if (!form.value.username || !form.value.password) {
    errorMessage.value = '请输入用户名和密码'
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }

  const data = {
    type: "REGISTER",
    payload: {
      username: form.value.username,
      password: form.value.password
    },
    timestamp: new Date().toISOString()
  };
  socket.send(JSON.stringify(data));
  // socket.addEventListener('message', (event) => {
  //   const response = JSON.parse(event.data);
  //   if (response.responseMsg === "注册成功") {
  //     errorMessage.value = '注册成功！';
  //     // 自动跳转到登录页面
  //     isRegistering.value = false;
  //   } else if (response.responseMsg === "用户名已存在") {
  //     errorMessage.value = '该用户名已被注册！';
  //   }
  // });
}

// 在组件挂载时添加事件监听
onMounted(() => {
  socket.addEventListener('message', messageHandler);
});

// 在组件卸载时移除事件监听
onUnmounted(() => {
  socket.removeEventListener('message', messageHandler);
});
</script>


<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin-left: 70px;
}

.login-container {
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
  width: 1000px;
  display: flex;
  overflow: hidden;
  transition: height 0.3s ease; /* 平滑过渡 */
}

.login-left {
  flex: 1;
  padding: 60px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.login-right {
  flex: 1;
  padding: 60px;
  background-color: #f8faf5;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 700px;
}

.brand-logo {
  text-align: center;
  margin-bottom: 40px;
}

.brand-logo img {
  width: 200px;
  height: 200px;
  margin-bottom: -93px;
}

.welcome-image {
  margin-bottom: 10px;
  width: 300px;
  height: 80px;
}

.welcome-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.subtitle {
  font-size: 30px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 20px;
  background: linear-gradient(45deg, #333, #95ec69);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

.brand-features {
  margin-top: 60px;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 13px;
  transform: translateX(0);
  transition: transform 0.3s ease;
}

.feature-item:hover {
  transform: translateX(10px);
}

.feature-icon {
  font-size: 32px;
  margin-right: 20px;
  transition: transform 0.3s ease;
}

.feature-item:hover .feature-icon {
  transform: scale(1.1);
}

.feature-item p {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  background: linear-gradient(45deg, #333, #95ec69);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

.input-group {
  margin-bottom: 15px;
}

.input-group input {
  width: 100%;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;
  background-color: #f8f8f8;
}

.input-group input:focus {
  border-color: #95ec69;
  outline: none;
}

.login-btn {
  width: 100%;
  padding: 15px;
  background-color: #95ec69;
  color: #333;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
}

.login-btn:hover {
  background-color: #86d35f;
}

.register-link {
  margin-top: 15px;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #95ec69;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}

.error-msg {
  color: red;
  font-size: 14px;
  margin-top: 10px;
}
</style>
